# 空字典
empty_dic = {}
print(f"empty_dic={empty_dic}")

# 使用dict()函数创建字典,根据列表元组来创建
new_dic = dict([("name", "bob"), ("age", 39), ("score", 98)])
print(f"new_dic={new_dic}")

# 根据键值参数对创建字典
dic_from_keys_value = dict(name="linda", age=39, score=88)
print(f"dic_from_keys_value={dic_from_keys_value}")

# 使用 fromkeys() 创建字典：所有键的值默认相同
keys = ["math", "english", "science"]
default_score = 60
score_dict = dict.fromkeys(keys, default_score)
print(score_dict)  # {'math': 60, 'english': 60, 'science': 60}

#
person_dic = {
    "name": "jackie",
    "age": 10,
    "score": 98.5,
    "favirote": ["music", "movie", "football"],
    ("alice", 10, 100): ("alice", 35, 100),
}

# 字典推导式:字典推导式（dict comprehension）用类似列表推导式的语法，快速批量生成字典。
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

new_nums_list = [num if num % 2 == 0 else num * 2 for num in nums]  # 列表推导式
print(f"new_nums_list={new_nums_list}")


nums_dict = {num: num if num % 2 == 0 else num * 2 for num in nums}  # 字典推导式
print(f"nums_dict={nums_dict}")


# 转换现有字典
original_dict = {"a": 1, "b": 2, "c": 3}
items = original_dict.items()  # [("a",1),("b",2),("c",3)]

for key, value in items:  # 等价于 for item in items的写法
    # key, value = item  # ("a",1) 对元组进行解包
    print(f"key={key},value={value}")

doubled_ditc = {key: value + 10 for key, value in original_dict.items()}
print(f"doubled_ditc={doubled_ditc}")


person = {"name": "Alice", "age": 30, "city": "Beijing"}

print(
    person.get("name"),
    person["age"],
    person.get("country", "找不到countrey就给默认值china"),
)


# 使用 update() 方法
person = {"name": "alice", "age": 29}
print(f"刚创建的person字典={person}")

# 用新字典更新老字典，重名的key就覆盖，不存在key就创建
person.update({"age": 100, "country": "中国"})
print(f"更新后的字典={person}")

del person["country"]  # 类似js的delete person["country"] | delete person.country

print(f"删除country之后的person={person}")

# 删除指定的键，并返回该键的值，告诉是删除了那一个

del_val = person.pop("name")
print(f"删除了={del_val}")


person = {"name": "Alice", "age": 30, "city": "Beijing", "job": "Engineer"}

# del 语句 - 删除指定键
del person["age"]
print(person)  # {'name': 'Alice', 'city': 'Beijing', 'job': 'Engineer'}

# pop() - 删除并返回指定键的值
city = person.pop("city")
print(city)  # "Beijing"
print(person)  # {'name': 'Alice', 'job': 'Engineer'}

# popitem() - 删除并返回最后一个键值对（Python 3.7+ 按插入顺序）
last_item = person.popitem()
print(last_item)  # ('job', 'Engineer')
print(person)  # {'name': 'Alice'}

# clear() - 清空字典
person.clear()
print(person)  # {}

person.setdefault("grade", "60")

print("person=", person)

# del 删除整个字典
del person

try:
    print(person)
except NameError as e:
    print(f"e={e}")
